/*
 * 著作权声明
 * Copyright (c) 2025.8 拾壹
 * 本代码为个人独立开发，未经本人书面许可，任何组织或个人不得擅自复制、修改、分发、用于商业用途。
 * 联系方式：sjw123521@qq.com
 */

package com.xmqsfsky1017.laicai;

import android.app.Dialog;
import android.content.Intent;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import androidx.constraintlayout.widget.ConstraintLayout;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;

public class MainActivity extends AppCompatActivity {

    private static final String AMOUNT_REGEX = "[-+]?([1-9]\\d*|0)(\\.\\d{1,2})?";

	ConstraintLayout clParent;
    EditText etInitialAssets;
    EditText etResult;
    EditText etBigWrite;
    Button btnOK;
    Button btnRmb100;
    Button btnRmb50;
    Button btnRmb20;
    Button btnRmb10;
    Button btnFaCai;
    Button btnRmb5;
    Button btnReduce;
    Button btnRmb1;
    Button btnRmb0_5;
    Button btnRmb0_1;
	Button btnZero;
	Button btnRmb6;
    Button btnMnyMoney;
	Button btnAbout;

    Map<Button, BaauzougungNumber> btnToMoney = new HashMap<>();
	Map<Button,String> btnToNum=new HashMap<>();
	Set<Button> btnsForMoney;
	Set<Button> btnsForNum;
	boolean posOrNeg=true;
	boolean isManyMoneying=false;
	boolean isMoneyChoosed=false;
	StringBuilder moneyCount=new StringBuilder();
	BaauzougungNumber totalMoney=new BaauzougungNumber("0");
    BaauzougungNumber choosedMoney=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etInitialAssets = findViewById(R.id.initialAssets);
        etResult = findViewById(R.id.result);
        etBigWrite = findViewById(R.id.bigWrite);
        btnOK = findViewById(R.id.ok);
        btnRmb100 = findViewById(R.id.rmb100);
        btnRmb50 = findViewById(R.id.rmb50);
        btnRmb20 = findViewById(R.id.rmb20);
        btnRmb10 = findViewById(R.id.rmb10);
        btnFaCai = findViewById(R.id.faCai);
        btnRmb5 = findViewById(R.id.rmb5);
        btnReduce = findViewById(R.id.reduce);
        btnRmb1 = findViewById(R.id.rmb1);
        btnRmb0_5 = findViewById(R.id.rmb0_5);
        btnRmb0_1 = findViewById(R.id.rmb0_1);
        btnMnyMoney = findViewById(R.id.mny_money);
		btnZero = findViewById(R.id.zero);
		btnRmb6 = findViewById(R.id.rmb6);
		clParent = findViewById(R.id.parent);
		btnAbout = findViewById(R.id.about);

        btnToMoney.put(btnRmb100, new BaauzougungNumber("100"));
        btnToMoney.put(btnRmb50, new BaauzougungNumber("50"));
        btnToMoney.put(btnRmb20, new BaauzougungNumber("20"));
        btnToMoney.put(btnRmb10, new BaauzougungNumber("10"));
        btnToMoney.put(btnRmb5, new BaauzougungNumber("5"));
        btnToMoney.put(btnRmb1, new BaauzougungNumber("1"));
        btnToMoney.put(btnRmb0_5, new BaauzougungNumber("0.5"));
        btnToMoney.put(btnRmb0_1, new BaauzougungNumber("0.1"));
		btnToMoney.put(btnRmb6,new BaauzougungNumber("6"));

        btnToNum.put(btnRmb100, "1");
        btnToNum.put(btnRmb50, "2");
        btnToNum.put(btnRmb20, "3");
        btnToNum.put(btnRmb10, "4");
        btnToNum.put(btnRmb5, "6");
        btnToNum.put(btnRmb1, "7");
        btnToNum.put(btnRmb0_5, "8");
        btnToNum.put(btnRmb0_1, "9");
		btnToNum.put(btnZero,"0");
        btnToNum.put(btnFaCai,"5");
        btnToNum.put(btnRmb6,"");

		btnsForMoney = btnToMoney.keySet();
		btnsForNum = btnToNum.keySet();

		btnReduce.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                posOrNeg = false;
                break;
                case MotionEvent.ACTION_UP:
                    posOrNeg=true;
			        break;
            }
            return true;
        });

		btnMnyMoney.setOnTouchListener((v,event)->{
			switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					isManyMoneying=true;
					break;
				case MotionEvent.ACTION_UP:
				    for (Map.Entry<Button,BaauzougungNumber> entry:btnToMoney.entrySet()) {
						Button b=entry.getKey();
						BaauzougungNumber money=entry.getValue();
						b.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
						b.setText(String.format("%s 元",money.toString()));
					}
                    btnFaCai.setTextSize(TypedValue.COMPLEX_UNIT_SP,9);
                    btnFaCai.setText(getString(R.string.facai_text));
					String num=moneyCount.toString();
					if (isMoneyChoosed&&moneyCount.length()!=0&&choosedMoney!=null) {
						BaauzougungNumber delta=choosedMoney.multiply(
						                            new BaauzougungNumber(num)
															         )
									                    	.multiply(
															    (posOrNeg?new BaauzougungNumber("1"):new BaauzougungNumber("-1"))
										            );
						setTotalMoney(totalMoney.add(delta));
					}
					isManyMoneying=isMoneyChoosed=false;
					choosedMoney=null;
					moneyCount.setLength(0);
			}
			return true;
		});

		etInitialAssets.setOnFocusChangeListener((v,hasFocus)->{
			EditText et=(EditText)v;
			if (hasFocus) return;
			String s=et.getText().toString().trim();
			if (!s.matches(AMOUNT_REGEX)) {
				new AlertDialog.Builder(this)
						.setTitle("错误")
						.setMessage("数字格式不对！")
						.setNeutralButton("确定",null)
						.setCancelable(false).show();
				return;
			}
	        if (s.isEmpty())et.setText("0");
		});

		btnFaCai.setOnClickListener(v->{
			if (!(isManyMoneying&&isMoneyChoosed)) {
				setTotalMoney(new BaauzougungNumber("0"));
			} else if (isManyMoneying&&isMoneyChoosed) {
				appendDigit("5");
			}
		});

		btnOK.setOnClickListener(v->{
			if (!etInitialAssets.getText().toString().matches(AMOUNT_REGEX)) {
				new AlertDialog.Builder(this)
						.setTitle("提示")
						.setMessage("不OK")
						.setPositiveButton("OK",null)
						.show();
						return;
			}
			setTotalMoney(new BaauzougungNumber(etInitialAssets.getText().toString()));
		});

	    setOnClickListenerForButtonsInLayout(clParent,v->{
			Button b=(Button)v;
			if (isManyMoneying&&!isMoneyChoosed){
				choosedMoney=btnToMoney.get(b);
				isMoneyChoosed=true;
				for (Map.Entry<Button,String> entry:btnToNum.entrySet()) {
						Button btn=entry.getKey();
						String num=entry.getValue();
						btn.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
						btn.setText(num);
				}
			}
			else if (isManyMoneying&&isMoneyChoosed) {
                String num = btnToNum.get(b);
                if (num != null) appendDigit(num);
            }
			else if (!(isManyMoneying&&isMoneyChoosed)) {
                BaauzougungNumber money = btnToMoney.get(b);
                if (money != null) {
                    BaauzougungNumber delta = posOrNeg ? money : money.multiply(new BaauzougungNumber("-1"));
                    setTotalMoney(totalMoney.add(delta));
                }
            }
		});
		
		btnAbout.setOnClickListener(v->{
			Intent intent=new Intent(this,AboutActivity.class);
			startActivity(intent);
		});
	}

    private void setOnClickListenerForButtonsInLayout(ViewGroup vg,View.OnClickListener oclr) {
		View child;
		for (int i=0;i<vg.getChildCount();i++) {
			child = vg.getChildAt(i);
			if (child instanceof ViewGroup) {
				setOnClickListenerForButtonsInLayout((ViewGroup)child,oclr);
			}
			if (child instanceof Button) {
				Button b=(Button)child;
				if (isSetedOnClickListener(b)) {continue;}
				b.setOnClickListener(oclr);
			}
		}
	}

	private boolean isSetedOnClickListener(Button b) {
		if (b==null) {throw new IllegalArgumentException("参数不可为空");}
	    try{
		    Method getListenerInfoMethod = View.class.getDeclaredMethod("getListenerInfo");
            getListenerInfoMethod.setAccessible(true);
            Object listenerInfo = getListenerInfoMethod.invoke(b);
    		Field onClickListenerField = listenerInfo.getClass().getDeclaredField("mOnClickListener");
            onClickListenerField.setAccessible(true);
            View.OnClickListener onClickListener = (View.OnClickListener) onClickListenerField.get(listenerInfo);
            boolean isClickListenerSet = onClickListener != null;
    		return isClickListenerSet;
		}catch (Exception e) {
			return false;
		}
	}

	private void setTotalMoney(BaauzougungNumber x) {
		totalMoney=x;
		etResult.setText(x.toString());
		etBigWrite.setText(x.toBigWrite());
	}

    private void appendDigit(String digit) {
        if (moneyCount.length() >= 6) {
			moneyCount=new StringBuilder("");
			new AlertDialog.Builder(this)
					.setTitle("错误")
					.setMessage("你这么多钱？吃不下啊，分几更喂吧。。。")
					.setPositiveButton("确定",null)
					.show();
		};
        if ("0".equals(digit) && moneyCount.length() == 0) return;
        moneyCount.append(digit);
    }
	
}
